var express = require('express');
var date = require("silly-datetime");
var router = express.Router();
const app = require('../app');
const Return = require('../util/utils');
let config = require('../config/index');
let request = require('request');
config = Object.assign({}, config.mp);
const {
    sqlConnect
} = require('../sql/sqlUtil');
const sqlUtil = require('../sql/sqlUtil');
// 是否展示图标
router.get('/showIcon', (req, res) => {
    var json = Return.setResult()
    json.show = 1;
    res.send(json);
})
// 获取学校名称
router.get("/school", function (req, res) {
    sqlConnect("select id,s_name from school where is_del=0;select * from system_data where is_del=1", function (err, data) {
        if (err) {
            return res.send(Return.setResult(500, "服务器繁忙请稍后再试"));
        }
        var json = Return.setResult();
        json.data = data;
        res.send(json);
    })
})
// 获取年级个数和班级个数
router.post("/school", function (req, res, next) {
    try {
        var sid = req.body.id;
        if (sid == undefined) {
            var json = Return.setResult();
            json.message = "error";
            res.send(json);
        } else {
            sqlConnect("select class_num as classNum,grade_num as gradeNum, level from school where id=?;select id,name from club where sid=? and is_del=0", [sid, sid], function (err, data) {
                if (err) {
                    console.log(err);
                } else {
                    res.send(Return.setResult(200, "success", data));
                }
            })

        }

    } catch (error) {
        console.log(error)
    }
})
// 获取openid
router.post("/login", (req, res) => {
    var nickname = req.body.nickname;
    var profile_url = req.body.profile_url;
    var code = req.body.code;
    // nickname=Buffer.from(nickname, 'base64');
    // nickname = new Buffer(nickname, 'base64').toString();
    if (!code) {
        var json = Return.setResult();
        json.code = 403;
        json.message = "code不能为空";
        res.send(json);
    } else {
        try {
            // 获取openid
            var sessionUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.appId}&secret=${config.appSecret}&js_code=${code}&grant_type=authorization_code`;
            request(sessionUrl, (err, response, body) => {
                if (!err && response.statusCode == 200) {
                    var json = Return.setResult();
                    var result = JSON.parse(body);

                    // 获取全局accessToken
                    var token = accessToken;

                    if (!result.errcode) {
                        var openid = result.openid;
                        // 判断是否已注册过（在数据库写入过openid）
                        sqlConnect(`select name from student where openid="${openid}"`, function (err, data) {
                            if (err) {
                                console.log(err)
                            } else {

                                if (data.length > 0) {
                                    if (data[0].name !== null) {
                                        data = JSON.parse(JSON.stringify(data));
                                        var sql = `update student set nickname="${nickname}",pf_img_url="${profile_url}" where openid="${openid}"`
                                        sqlConnect(sql, function (err) {
                                            if (err) {
                                                console.log(err);
                                            }
                                            json.message = "登录成功";
                                            json.name = data[0].name;
                                            json.flag = 1;
                                            data = {
                                                "openid": openid
                                            };
                                            json.data = data;
                                            res.send(json);
                                        })
                                    } else {
                                        json.message = "登录成功";
                                        var data = {
                                            "openid": openid
                                        };
                                        json.flag = 0;
                                        json.data = data;
                                        res.send(json);
                                    }

                                } else {
                                    sql = `insert into student (openid,nickname,pf_img_url,is_del) values("${openid}","${nickname}","${profile_url}",0)`
                                    sqlConnect(sql, function (err) {
                                        if (err) {
                                            console.log(err);
                                        } else {
                                            json.message = "登录成功";
                                            var data = {
                                                "openid": openid
                                            };
                                            json.flag = 0;
                                            json.data = data;
                                            res.send(json);
                                        }
                                    });
                                }
                            }
                        })

                        // 获取手机号
                        // var requestData={"code":code};
                        // request({
                        //     url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${token}`, //url
                        //     method: "POST",
                        //     json: true,
                        //     headers: {
                        //         "content-type": "application/json",
                        //     },
                        //     body: JSON.stringify(requestData)

                        // }, function (error, response, body) {
                        //     if (!error && response.statusCode == 200) {
                        //         console.log(body)
                        //         var data = JSON.parse(JSON.stringify(body));
                        //         console.log(data.errcode)
                        //         // if (data.errcode == 0) {
                        //         //     var mobile = data.phone_info.phoneNumber;
                        //         //     // 插入学生信息
                        //         //     var sql = `insert into student (openid,nickname,pf_img_url,mobile) values(${openid},${nickname},${profile_url},${mobile})`
                        //         //     sqlUtils.sqlConnect(sql, function (err) {
                        //         //         if (err) {
                        //         //             console.log(err);
                        //         //         } else {
                        //         //             json.message = "登录成功";
                        //         //             var data = {
                        //         //                 "openid": openid
                        //         //             };
                        //         //             json.data = data;
                        //         //             res.send(json);
                        //         //         }
                        //         //     });
                        //         // } else {
                        //         //     console.log("获取手机号");
                        //         //     console.log(data)
                        //         //     console.log("--------")
                        //         // }
                        //     } else {
                        //         console.log("error");
                        //     }
                        // });
                    } else {
                        json.code = result.errcode;
                        json.message = result.errmsg;
                        res.send(json);
                    }
                } else {
                    console.log("请求1:" + err)
                }
            })
        } catch (err) {
            console.log("try:" + err);
        }
    }
})
// 提交支付信息
router.post("/payment", function (req, res) {
    try {
        var json = Return.setResult();
        // console.log(req.body.openid);
        if (req.body.openid) {
            var openid = req.body.openid,
                school = req.body.school,
                grade = req.body.grade,
                className = req.body.className,
                name = req.body.name,
                amount = req.body.amount,
                mobile = req.body.mobile,
                tip = (req.body.tip) ? req.body.tip : "",
                pay_img_url = req.body.img_url,
                club = req.body.club;
            var time = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
            var sql = "update student set name=?,mobile=? where openid=?"
            var sqlArr = [name, mobile, openid];
            sqlConnect(sql, sqlArr, function (err) {
                if (err) {
                    console.log("第一:" + err)
                } else {
                    sqlConnect(`select id from student where openid="${openid}"`, function (err, data) {
                        if (err) {
                            console.log("第二:" + err);
                        } else {
                            try {
                                var id = data[0].id;
                                sql = `insert into payment (stu_id,amount,pay_time,pay_img_url,tip,club,school,grade,class_name,is_del,status) values(?,?,?,?,?,?,?,?,?,0,0)`
                                sqlConnect(sql, [id, amount, time, pay_img_url, tip, club, school, grade, className], function (err) {
                                    if (err) {
                                        console.log("第三:" + err)
                                    } else {
                                        res.send(json);
                                    }
                                })

                            } catch (err) {
                                json.code = 40111;
                                json.message = "openid不存在"
                                res.send(json);
                            }
                        }
                    })


                }
            })
        } else {
            json.code = 40111;
            json.message = "请求数据格式错误，应为json格式"
            res.send(json);
        }

    } catch (error) {
        console.log(error);
    }
})
// 提交请假信息
router.post('/leave', (req, res) => {
    let begin_date = req.body.begin_date,
        end_date = req.body.end_date,
        openid = req.body.openid,
        name = req.body.name,
        school = req.body.school,
        grade = req.body.grade,
        class_name = req.body.class_name
    club = req.body.club;
    var json = Return.setResult();
    var sql = "update student set name=? where openid=?"
    var sqlArr = [name, openid];
    sqlConnect(sql, sqlArr, function (err) {
        if (err) {
            console.log("第一:" + err)
        } else {
            sqlConnect(`select id from student where openid="${openid}"`, function (err, data) {
                if (err) {
                    console.log("第二:" + err);
                } else {
                    try {
                        var id = data[0].id;
                        sql = 'insert into leave_info (stu_id,begin_date,end_date,club,school,grade,class_name,is_del) values(?,?,?,?,?,?,?,0)'
                        sqlConnect(sql, [id, begin_date, end_date, club, school, grade, class_name], function (err) {
                            if (err) {
                                console.log("第三:" + err)
                            } else {
                                res.send(json);
                            }
                        })

                    } catch (err) {
                        json.code = 40111;
                        json.message = "openid不存在"
                        res.send(json);
                    }
                }
            })


        }
    })
})
// 获取请假信息
router.get("/leaveInfo", (req, res) => {
    var openid = req.query.openid;
    if (!openid) {
        return res.send(Return.setResult(500, '无法获取到所传openid'))
    }
    let sql = "select a.id,a.club,a.begin_date,a.end_date,b.name,a.school,a.grade,a.class_name from leave_info as a inner join student as b on a.stu_id=b.id and a.is_del=0 and b.openid=? order by 1 desc";
    sqlConnect(sql, [openid], function (err, data) {
        if (err) {
            return res.send(Return.setResult(500, "openid错误或不存在"));
        }
        var json = Return.setResult();
        json.data = data;
        res.send(json);
    })
})
// 修改请假信息
router.post('/change-leaveInfo', (req, res) => {
    const id = req.body.id,
        begin_date = req.body.begin_date,
        end_date = req.body.end_date;
    if (!id)
        return res.send(Return.setResult(40111, "id不能为空"));
    sqlConnect("update leave_info set begin_date=?,end_date=? where id=?", [begin_date, end_date, id], (err) => {
        if (err)
            return console.log(err);
        res.send(Return.setResult());
    })
})
// 取消请假
router.delete('/cancel', (req, res) => {
    const id = req.body.id;
    if (!id) {
        return res.send(Return.setResult(500, "无法获取到所传id"));
    }
    sqlConnect("DELETE FROM leave_info WHERE id=?", [id], (err, data) => {
        if (err) {
            return res.send(Return.setResult(500, "id不存在"))
        }
        res.send(Return.setResult())
    })
})
// 查询缴费信息
router.get('/paymentInfo', (req, res) => {
    var openid = req.query.openid;
    if (!openid) {
        return res.send(Return.setResult(500, '无法获取到所传openid'))
    }
    var sql = "select a.id,a.club,a.amount,a.status,a.pay_time,b.name,a.school from payment as a inner join student as b on a.stu_id=b.id and a.is_del=0 and b.openid=? order by 1 desc ";
    sqlConnect(sql, [openid], function (err, data) {
        if (err) {
            return res.send(Return.setResult(500, "openid错误或不存在"));
        }
        var json = Return.setResult();
        json.data = data;
        res.send(json);
    })
})
// 获取新闻列表
router.get('/newsList', function (req, res, next) {
    try {
        //    var sql = "select id,title,date,author,has_img,news_img from news where is_del=0 and title is not null order by 1 desc";
        sqlConnect("select id,title,date,author,has_img,news_img from news where is_del=0 and is_pass=1 order by 1 desc", function (err, data) {
            if (err) {
                console.log(err);
            } else {
                res.send(Return.setResult(200, "success", data));
            }
        })
    } catch (error) {
        res.send(Return.setResult(500, "网络拥堵，请稍后再试！"))
    }

});
// 获取指定新闻
router.get("/news", (req, res) => {
    let id = req.query.id;
    sqlConnect("update news set read_amount=read_amount+1 where id=?", id, (err, data) => {
        if (err) {
            return console.log(err);
        }
        sqlConnect("select * from news where id=?", id, (err, data) => {
            if (err) {
                return console.log(err);
            }
            return res.send(Return.setResult(200, "success", data));
        })
    })

})
// 轮播图
router.get("/", (req, res) => {
    sqlConnect("select id,news_img from news where is_del=0 and is_using=1 order by 1 desc", (err, data) => {
        if (err) {
            return console.log(err);
        }
        return res.send(Return.setResult(200, "success", data));
    })

})
module.exports = router;